package com.android.duininsuoai.app;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.duininsuoai.R;
import com.android.duininsuoai.activity.MainTab;
import com.android.duininsuoai.activity.mine.LoginActivity;
import com.android.duininsuoai.model.WinnerObservable;
import com.android.duininsuoai.model.WinnerObserver;
import com.android.duininsuoai.model.group.MainNewOrderMsgData;
import com.android.duininsuoai.model.group.MainNewOrderMsgDataCallback;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.LoginState;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;
import com.android.duininsuoai.utils.ReleaseManager;
import com.android.duininsuoai.view.dialog.CustomToast;
import com.elbbbird.android.socialsdk.otto.BusProvider;

import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

public class BaseActivity extends AppCompatActivity {
    private boolean isshow = false;
    private CustomToast customToast;
    private BaseActivity.task task;
    private BaseActivity mcontext;
    private AlertDialog dialog;

    private WinnerObserver winnerObserver = new WinnerObserver() {
        @Override
        public void update(Observable o, Object arg) {
            //观察者接受到被观察者的通知，更新中奖信息
            super.update(o, arg);
            WinnerObservable winnerObservable = (WinnerObservable) o;
            String notify_title = winnerObservable.getNotify_title();
            NotifyDialog(notify_title);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        makeLogTag();
        mcontext = BaseActivity.this;
        customToast = new CustomToast(mcontext, "", "", 356);
        isshow = false;
        BusProvider.getInstance().register(mcontext);
    }

    /**
     * 设置状态栏 返回键
     */
    public void initTitle(int type, String title) {
        //设置状态栏颜色

        ObjectUtils.StatusBarWhiteBg(mcontext, false);
        ImageView main_top_back = (ImageView) findViewById(R.id.main_top_back);
        TextView main_top_title = (TextView) findViewById(R.id.main_top_title);
        main_top_back.setVisibility(View.VISIBLE);
        main_top_title.setText(title);
        main_top_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    /**
     * 最新订单全局显示
     */
    private void MonitorNetwork() {
        task = new task();
        boolean networkConnected = ObjectUtils.isNetworkConnected(BaseActivity.this);
        if (networkConnected) {
            MyLog.e("开启订单刷新", "开启订单刷新");
            // timer.schedule(task, 10000, 30000);
        }
    }

    //定时获取
    private void GetData() {
        String address = ConstantsUrl.domain + "goods/order_notice";
        HttpUtils.get(address, null, new MainNewOrderMsgDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(MainNewOrderMsgData response, int id) {
                if (response.getData() != null) {
                    MyLog.e("e", "" + response.toString());
                    customToast = new CustomToast(BaseActivity.this, response.getData().getMessage(), response.getData().getAvatar(), response.getData().getId());
                    customToast.show();
                    showmsghander.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (!isshow) {
                                customToast.dismiss();
                            }
                        }
                    }, 3000);


                }
            }
        });
    }

    Handler showmsghander = new Handler();
    //定时刷新
    Timer timer = new Timer();

    class task extends TimerTask {


        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    update();
                    break;
            }
            super.handleMessage(msg);
        }

        void update() {
            if (!isshow) {
                GetData();
            }
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        isshow = false;
        MonitorNetwork();
        //观察者往被观察者中添加订阅事件。
        WinnerObservable.getInstance().addObserver(winnerObserver);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isshow = true;
        customToast.dismiss();
        if (task != null) {
            task.cancel();  //将原任务从队列中移除
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isshow = true;
        customToast.dismiss();
        //观察者从被观察者队列中移除
        WinnerObservable.getInstance().deleteObserver(winnerObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isshow = true;
        customToast.dismiss();
        BusProvider.getInstance().unregister(mcontext);
    }


    /**
     * Administrator2013-11-22 上午2:16:45
     *
     * @return String
     * TODO 打印
     */
    public void makeLogTag() {
        ReleaseManager.printLog(getClass().getSimpleName(), getClass().toString() + "---Acvitiy start");
    }

    public void makeLogTag(String str) {
        ReleaseManager.printLog(getClass().toString(), str);
    }

    /**
     * 领奖通知
     */
    public void NotifyDialog(String notify_title) {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_notify_congraturation, null);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView dialog_cancel = (TextView) v.findViewById(R.id.dialog_cancel);
        TextView content = (TextView) v.findViewById(R.id.dialog_content);
        content.setText("恭喜您，获得" + Html.fromHtml(notify_title) + "\n马上领取吗？");
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog.dismiss();
                                        if (LoginState.getInstance().isLogin(mcontext)) {
                                            Intent intent = new Intent(mcontext, MainTab.class);
                                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, 2);
                                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, 4);
                                            startActivity(intent);
                                        } else {
                                            startActivity(new Intent(mcontext, LoginActivity.class));
                                        }
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }
}



